filename = 'buffer://localhost:1972';
host='localhost';
port=1972;
if  ~exist('duration','var'),
    duration = 30;
end
doSendTrigger = true;
if doSendTrigger,
    sendTrigger(0,'DIO'); % 'DIO' or parallelport number (378)    
end
headerRefresh=0.1;
triggerChan = []; % triggerchannel BTI-MEG:1, don't read evebts: []; % use read_event: 0
trigChanOrder = [1,2,3,4]; % see bciAnalog2Trig
hdr=read_header(filename);
offset = hdr.nSamples/hdr.Fs;
skipSamples = hdr.nSamples;
begsample=hdr.nSamples+1;
t0=GetSecs;
startHeaderRead=t0;
lastReadTime=t0;
curS=skipSamples;
maxSamples=floor(duration*hdr.Fs);
maxBlocks = floor((duration+10)/headerRefresh);
dat=zeros(hdr.nChans,maxSamples);
timingLog=zeros(maxBlocks,3);
trigDelay=zeros(maxBlocks,1);
trigRec=zeros(maxBlocks,1);
trigSent=zeros(maxBlocks,1);
trigPos= zeros(maxBlocks,1);
trigSentTime = zeros(maxBlocks,1);
trigRecTime = zeros(maxBlocks,1);

idleTime = 0;
nTrigRec = 0;
readHdrTime=0;
lastReadEvent = -1;
k=0;

while curS-skipSamples<maxSamples,
    %hdr=read_header(filename);
    if GetSecs-startHeaderRead>=headerRefresh*0.5,
        startHeaderRead=GetSecs;    
        %orig = buffer('get_hdr', [], host, port);
        nextSample = begsample + round(headerRefresh*hdr.Fs)-1;
        try
            tmpDat=buffer('get_dat', [begsample nextSample], host, port);
            hdr.nSamples=nextSample;
        catch
            fprintf('waiting for data\n');
        end
        readHdrTime=readHdrTime+(GetSecs-startHeaderRead);
%        hdr.nSamples=orig.nsamples;
    end
    if hdr.nSamples>curS,
        k=k+1;
        % send trigger
        if doSendTrigger,
            %trigSent(nTrigRec+1)=ceil(rand(1)*254);
            trigSent(nTrigRec+1)=mod(nTrigRec,255)+1;
            sendTrigger(trigSent(nTrigRec+1));
            trigSentTime(nTrigRec+1)=GetSecs;
            doSendTrigger = false;
            fprintf('Trigger sent: %i\n',trigSent(nTrigRec+1));
        end
        % read data from buffer
        nextReadTime=GetSecs;
        newS = hdr.nSamples-curS;
        curS=hdr.nSamples;
%        tmpDat=buffer('get_dat', [begsample curS], host, port);
        dat(:,(begsample:curS)-skipSamples)= tmpDat.buf;
%         dat(:,(begsample:curS)-skipSamples)=read_data(filename, ...
%             'header', hdr, 'begsample', begsample, 'endsample', curS);
        idle = (nextReadTime-lastReadTime)-readHdrTime;
        idleTime=idleTime+idle;
        % test for trigger in data
        if ~isempty(triggerChan),
            if triggerChan==0,
                try
                    evt = buffer('get_evt', [nTrigRec nTrigRec], 'localhost', 1972);
                    nTrigRec = nTrigRec+1;
                    trigRecTime(nTrigRec)=GetSecs;
                    trigDelay(nTrigRec) = (trigRecTime(nTrigRec)-trigSentTime(nTrigRec));
                    trigRec(nTrigRec) = evt.buf(end);
                    trigPos(nTrigRec) = evt.sample-begsample;
                    doSendTrigger=true;
                    fprintf('Trigger received: %i delay: %1.3f\n',...
                        trigRec(nTrigRec),trigDelay(nTrigRec));
                catch
                end                    
                %trig = read_event(filename, 'header', hdr);
            else
                if size(triggerChan)>1,
                    trigData = bciAnalog2Trig(dat(triggerChan,(begsample:curS)-skipSamples),trigChanOrder);
                else
                    trigData = dat(triggerChan,(begsample:curS)-skipSamples);
                end
                tmp=find(trigData>0);
                if ~isempty(tmp),
                   % fprintf(tmp(1))
                    nTrigRec = nTrigRec+1;
                    trigRecTime(nTrigRec)=GetSecs;
                    trigDelay(nTrigRec) = (trigRecTime(nTrigRec)-trigSentTime(nTrigRec));
                    trigRec(nTrigRec) = trigData(tmp(1));
                    trigPos(nTrigRec) = tmp(1);
                    doSendTrigger=true;
                    fprintf('Trigger sent: %i delay: %1.3f\n',...
                        dat(triggerChan,(begsample)-skipSamples+tmp(1)),trigDelay(nTrigRec));
                end
            end
        end
        % log timing
        timingLog(k,:)=[curS,curS/hdr.Fs,(GetSecs-t0)+offset];
        fprintf('nSamples: %i BufferTime: %3.3f CPUTime: %3.3f idle: %1.3f\n',...
            curS,timingLog(k,2),timingLog(k,3),idle);
        begsample = curS+1;
        readHdrTime=0;
        lastReadTime=GetSecs;
    end
end
trigDelay(nTrigRec+1:end)=[];
trigRec(nTrigRec+1:end)=[];
trigSent(nTrigRec+1:end)=[];
trigSentTime(nTrigRec+1:end)=[];
trigRecTime(nTrigRec+1:end)=[];
trigPos(nTrigRec+1:end)=[];
if nTrigRec>0,
    meanDelay = mean(trigDelay);
end
dat=dat(:,1:curS-skipSamples);
timingLog(k+1:end,:)=[];

fprintf('Time left for calculation: %3.3fs = %2.1f%%\n',idleTime,idleTime/(size(dat,2)/hdr.Fs)*100);
